<template>
    <el-card v-loading="loading">
        <template #header>
            <el-button type="primary" :icon="Plus" @click="dialogVisible = true">添加</el-button>
        </template>
        <el-table :data="trademarkList" border style="width: 100%" class="mb-10">
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="tmName" label="品牌名称" />
            <el-table-column prop="tmLogo" label="品牌LOGO">
                <template #default="{ $index, row }">
                    <img :src="row.logoUrl" alt="暂无数据" width="80" height="80">
                </template>
            </el-table-column>
            <el-table-column prop="操作" label="操作">
                <template #default="{ $index, row}">
                    <el-button size="default" type="warning" :icon="Edit" @click="handleEdit($index, row)">编辑
                    </el-button>
                    <el-button size="default" type="danger" :icon="Delete" @click="handleDelete($index, row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:currentPage="page" v-model:page-size="limit" :page-sizes="[3, 6, 9]"
            layout="prev, pager, next, jumper,->,sizes,total" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        <el-dialog v-model="dialogVisible" :title="tmForm.id ? '修改品牌' : '添加品牌'" @close="resetForm(ruleFormRef)">
            <el-form :model="tmForm" style="width: 500px;" label-width="100px" ref="ruleFormRef" :rules="rules">
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input v-model="tmForm.tmName" placeholder="请输入品牌名称" />
                </el-form-item>
                <el-form-item label="品牌LOGO" prop="logoUrl">
                    <el-upload class="avatar-uploader" :action="action" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">
                                上传图片必须是jpg且不能大于2M
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts" >
import { onMounted, reactive, ref } from 'vue';
import trademarkApi, { type trademarkModel } from '@/api/trademark';
import { ElMessage, ElMessageBox, type UploadProps } from 'element-plus';
import { Delete, Edit, Plus } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus'
import { cloneDeep } from 'lodash'
// 获取数据
onMounted(() => {
    getTrademarkPage();
})
// 用于初始化tmForm
const resetTmForm = () => ({
    tmName: '',
    logoUrl: ''
})
// 初始化数据
const page = ref(1)
const limit = ref(3)
const total = ref(0)
const trademarkList = ref<trademarkModel[]>()
const tmForm = ref<trademarkModel>(resetTmForm())
const dialogVisible = ref(false);
const ruleFormRef = ref<FormInstance>()
const action = `${import.meta.env.VITE_API_URL}/admin/product/upload`
const loading = ref(false)
// 发送请求
const getTrademarkPage = async () => {
    loading.value = true
    try {
        let result = await trademarkApi.getTrademarkPage(page.value, limit.value)
        total.value = result.total
        trademarkList.value = result.records
        loading.value = false
    } catch (error) {
        ElMessage.error('获取品牌失败,')
        loading.value = false
    }
}
// 编辑
const handleEdit = async (index: number, row: trademarkModel) => {
    dialogVisible.value = true;
    tmForm.value = cloneDeep(row);
}
// 删除
const handleDelete = async (index: number, row: trademarkModel) => {
    try {
        await ElMessageBox.confirm(
            `确认要删除[${row.tmName}]吗?`,
            '警告',
            {
                confirmButtonText: 'OK',
                cancelButtonText: 'Cancel',
                type: 'warning',
            }
        )
        await trademarkApi.remove(row.id as number)
        getTrademarkPage();
    } catch (error) {
        if (error === 'cancel') return
        ElMessage.error('删除失败,请重试')
    }
}
// 翻页
const handleCurrentChange = (val: number) => {
    page.value = val
    getTrademarkPage();
}
// 修改展示条数
const handleSizeChange = (val: number) => {
    limit.value = val
    getTrademarkPage();
}
// 上传的数据展示
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    tmForm.value.logoUrl = response.data;
    (ruleFormRef.value as FormInstance).validateField("logoUrl", (valid) => {});
}
// 上传的简单校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片必须是JPG格式');
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不得超过2M')
        return false
    }
    return true
}
// 保存数据
const onsave = async () => {
    try {
        if (tmForm.value.id) {
            await trademarkApi.update(tmForm.value)
        } else {
            await trademarkApi.save(tmForm.value);
        }
        resetForm(ruleFormRef.value);
    } catch (error) {
        ElMessage.error('保存品牌失败,请重试')
    }
}
// 设定规则
const rules = reactive<FormRules>({
    tmName: [
        { required: true, message: '请输入品牌名称', trigger: 'blur' },
        { min: 2, message: '品牌名称不得少于两个字符', trigger: 'blur' },
    ],
    logoUrl: [
        { required: true, message: '请上传图片', trigger: 'change' },
    ],
})
// 提交表单数据
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            onsave();
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 关闭dialog,清空表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogVisible.value = false;
    tmForm.value = resetTmForm();
    getTrademarkPage();
}

</script>
  
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>